package admin

import (
	"net/http"

	"github.com/google/uuid"
	"github.com/labstack/echo/v4"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/server/response"
)

// GetClientMessages 获取客户端消息列表
func (h *AdminHandler) GetClientMessages(c echo.Context) error {
	reqDto := new(GetClientMessagesRequest)
	if err := c.Bind(reqDto); err != nil {
		return response.BadRequest(c, "Invalid request format")
	}

	if reqDto.Page <= 0 {
		reqDto.Page = 1
	}
	if reqDto.Limit <= 0 || reqDto.Limit > 100 {
		reqDto.Limit = 20
	}

	var dbRows []entity.ClientMessage
	var total int64

	tx := h.db.Model(&entity.ClientMessage{})
	if reqDto.ConversationID != "" {
		tx = tx.Where("conversation_id = ?", reqDto.ConversationID)
	}

	// 获取总数
	if err := tx.Count(&total).Error; err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, "Database error")
	}

	// 获取消息列表
	offset := (reqDto.Page - 1) * reqDto.Limit
	if err := tx.Order("created_at DESC").
		Offset(offset).
		Limit(reqDto.Limit).
		Find(&dbRows).Error; err != nil {
		return echo.NewHTTPError(http.StatusInternalServerError, "Database error")
	}

	// 转换为响应格式
	rows := make([]ClientMessageRow, 0, len(dbRows))
	for _, msg := range dbRows {
		row := ClientMessageRow{
			ID:             msg.ID,
			Content:        msg.Content,
			Role:           msg.Role,
			CreatedAt:      msg.CreatedAt.Unix(),
			ConversationID: msg.ConversationID,
		}

		// 添加扩展字段（如果存在）
		if msg.Status != "" {
			statusStr := string(msg.Status)
			row.Status = &statusStr
		}
		if msg.ProcessingTime > 0 {
			row.ProcessingTime = &msg.ProcessingTime
		}
		if msg.Model != "" {
			row.Model = &msg.Model
		}
		if msg.TokensUsed > 0 {
			row.TokensUsed = &msg.TokensUsed
		}
		if msg.ErrorMessage != "" {
			row.ErrorMessage = &msg.ErrorMessage
		}

		rows = append(rows, row)
	}
	return response.Success(c, GetClientMessagesResponse{
		Rows:       rows,
		Total:      total,
		Page:       reqDto.Page,
		Limit:      reqDto.Limit,
		TotalPages: (total + int64(reqDto.Limit) - 1) / int64(reqDto.Limit),
	})
}

// GetClientMessageDetail 获取客户端消息详情
func (h *AdminHandler) GetClientMessageDetail(c echo.Context) error {
	messageIDStr := c.Param("id")
	if messageIDStr == "" {
		return response.BadRequest(c, "Message ID is required")
	}

	// 解析UUID
	messageID, err := uuid.Parse(messageIDStr)
	if err != nil {
		return response.BadRequest(c, "Invalid message ID format")
	}

	var message entity.ClientMessage
	if err := h.db.First(&message, "id = ?", messageID).Error; err != nil {
		return response.NotFound(c, "Message not found")
	}

	// 转换为详情响应格式
	detail := ClientMessageDetail{
		ClientMessageRow: ClientMessageRow{
			ID:             message.ID,
			ConversationID: message.ConversationID,
			Role:           message.Role,
			Content:        message.Content,
			CreatedAt:      message.CreatedAt.Unix(),
		},
		UserID:    message.UserID,
		UpdatedAt: message.UpdatedAt.Unix(),
	}

	// 添加扩展字段（如果存在）
	if message.Status != "" {
		statusStr := string(message.Status)
		detail.Status = &statusStr
	}
	if message.ProcessingTime > 0 {
		detail.ProcessingTime = &message.ProcessingTime
	}
	if message.Model != "" {
		detail.Model = &message.Model
	}
	if message.TokensUsed > 0 {
		detail.TokensUsed = &message.TokensUsed
	}
	if message.ErrorMessage != "" {
		detail.ErrorMessage = &message.ErrorMessage
	}

	return response.Success(c, detail)
}
